<template>
    <el-select v-model="formData" placeholder="请选择" clearable @change="dataChange" v-if="props.formType == 'select'">
        <el-option
            v-for="dict in dictOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
    </el-select>    
    <el-radio-group v-model="formData" v-else-if="props.formType == 'radio'">
        <el-radio
            v-for="dict in dictOptions"
            :key="dict.value"
            :label="dict.value"
        >{{dict.label}}</el-radio>
    </el-radio-group>
    <el-checkbox-group v-model="formData" v-else-if="props.formType == 'checkbox'">
        <el-checkbox 
            :label="dict.label"
            :value="dict.value"
            v-for="dict in dictOptions"
            :key="dict.value"/>
    </el-checkbox-group>
</template>

<script setup>
import useDictStore from '@/store/modules/dict';
import { getDicts } from '@/api/system/dict/data';

const emit = defineEmits(['update'])

const dictOptions = ref([]);
const formType = ref('select');
const formData = ref(null);

const props = defineProps({
  modelValue: [String, Number, Array],
  // 字典选项
  dictType: {
    type: Array,
    required: true,
  },
  // 展示方式
  formType: {
    type: String,
    default: 'select',
  },
  separator: {
    type: String,
    default: ",",
  }
});


watch(() => props.dictType, val => {
  if (val) {
    loadDict(props.dictType);
  } else {
    dictOptions.value = [];
  }
},{ deep: true, immediate: true });


watch(() => props.modelValue, val => {
  if (val) {
      if(props.formType == 'checkbox' || props.formType == 'tag'){
          formData.value = props.modelValue.split(props.separator);
      }else{
          formData.value = val;
      }
  } else {
      if(props.formType == 'checkbox'){
          formData.value = [];
      }else{
          formData.value = null;
      }
    return formData.value;
  }
},{ deep: true, immediate: true });

/** 加载字典 */
function loadDict(dictType) {
    const dicts = useDictStore().getDict(dictType);
    if (dicts) {
        dictOptions.value = dicts;
    } else {
        getDicts(dictType).then(resp => {
            dictOptions.value = resp.data.map(p => ({ label: p.dictLabel, value: p.dictValue, elTagType: p.listClass, elTagClass: p.cssClass }))
            useDictStore().setDict(dictType, dictOptions.value);
        });
    }
}

function dataChange() {        
    if(props.formType == 'checkbox'){
    emit("update:modelValue", formData.value.join(props.separator));
    }else{
    emit("update:modelValue", formData.value);
    }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
